<template>
  <div>2024-05-04的前7天，包含自身: <br />{{ beforeNDay('2024-05-04', 7, true) }}</div>
  <br />
  <div>2024-05-04的前7天，不包含自身: <br />{{ beforeNDay('2024-05-04', 7, false) }}</div>
  <br />
  <div>2024-01-01的前7天，不包含自身: <br />{{ beforeNDay('2024-01-01', 7, true) }}</div>
  <br />
  <div>2024-01-01的前7天，不包含自身: <br />{{ beforeNDay('2024-01-01', 7, false) }}</div>
</template>

<script setup>
import dayjs from 'dayjs'
import isSameOrBefore from 'dayjs/plugin/isSameOrBefore'
import 'dayjs/locale/zh-cn'
dayjs.locale('zh-cn')
dayjs.extend(isSameOrBefore)

/**
 * 获取指定日期前N天
 *
 * @param dateStr 指定日期. 格式: YYYY-MM-DD. 如: 2011-03-15
 * @param dayCount 前N天
 * @param containSelf 是否包含自身. 默认:false
 */
function beforeNDay(dateStr, dayCount, containSelf = false) {
  const date = dayjs(dateStr)
  const realDayCount = containSelf ? dayCount - 1 : dayCount
  let startDate = date.subtract(realDayCount, 'day')

  let loopStartDate = startDate
  const allDateArr = []

  if (containSelf) {
    while (loopStartDate.isSameOrBefore(date)) {
      allDateArr.push(loopStartDate.format('YYYY-MM-DD'))
      loopStartDate = loopStartDate.add(1, 'day')
    }
  } else {
    while (loopStartDate.isBefore(date)) {
      allDateArr.push(loopStartDate.format('YYYY-MM-DD'))
      loopStartDate = loopStartDate.add(1, 'day')
    }
  }
  return allDateArr
}
</script>
